package com.cndongtai.net.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisServer {
	
	private static RedisServer redisServer = null;
	
	private JedisPool pool;
	
	private RedisServer() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(20);
		config.setMaxIdle(5);
		config.setMinIdle(1);
		
//		pool = new JedisPool(config, "192.168.0.110",6379,3000, "redisadmin");
		pool = new JedisPool(config, "127.0.0.1",6379,3000, "success");
	}
	
	public static RedisServer getInstance() {
		if(redisServer==null) {
			redisServer = new RedisServer();
		}
		
		return redisServer;
	}
	
	public void set(String key, String value) {
		Jedis jedis = pool.getResource();
		try {
			jedis.set(key, value);
		}catch(Exception e) {
			throw e;
		}finally {
			jedis.close();
		}
	}
	
	public void set(String key, String value, int second) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			jedis.setex(key, second, value);
		}catch(Exception e) {
			System.out.println("==========================Redis服务宕机=======================");
			e.printStackTrace();
		}finally {
			if(jedis!=null) {
				jedis.close();
			}
		}
	}
	
	public String get(String key) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			return jedis.get(key);
		}catch(Exception e) {
			System.out.println("==========================Redis服务宕机=======================");
			e.printStackTrace();
			return null;
		}finally {
			if(jedis!=null) {
				jedis.close();
			}
		}
	}
	
	public Long del(String key) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			return jedis.del(key);
		}catch(Exception e) {
			System.out.println("==========================Redis服务宕机=======================");
			e.printStackTrace();
			return null;
		}finally {
			if(jedis!=null) {
				jedis.close();
			}
		}
	}

}
